<template>
  <div class="publicpageview">
    <div class="publicformview">
      <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发布主题：" prop="releaseTitle">
              <el-input v-model="listQuery.releaseTitle" placeholder="请输入发布主题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="文件来源单位：" prop="sourceUnit">
              <CompanySelect v-model="listQuery.sourceUnit"  />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="接收单位：" prop="receivingUnit">
              <CompanySelect v-model="listQuery.receivingUnit"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发布时间：" prop="releaseDate">
              <el-date-picker
                v-model="listQuery.releaseDate"
                type="date"
                placeholder="开始日期"
                value-format="yyyy-MM-dd"
                style="width: 45%">
              </el-date-picker>
              <span style="margin: 0 8px;">~</span>
              <el-date-picker
                v-model="listQuery.releaseEndDate"
                type="date"
                placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 45%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        
          <el-col style="text-align: right;" :span="24">
            <div>
              <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
              <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
        </div>
        
    <div class="publitableview">
      <el-button type="primary" size="mini" @click="handleAddRecord">新建发布</el-button>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row size="mini">
        <el-table-column align="center" label="序号" type="index" width="60">
        </el-table-column>

        <el-table-column align="center" label="文件来源单位" prop="sourceUnit" min-width="120">
          <template slot-scope="scope">
          <CompanySelect v-model="scope.row.sourceUnit" :disabled="true" />
        </template>
        </el-table-column>

        <el-table-column align="center" label="接收单位" prop="receivingUnit" min-width="120">
          <template slot-scope="scope">
            <CompanySelect v-model="scope.row.receivingUnit" :disabled="true" multiple/>
          </template>
        </el-table-column>

        <el-table-column align="center" label="发布日期" prop="releaseDate" width="100">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.releaseDate) }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="发布主题" prop="releaseTitle" min-width="200">
        </el-table-column>

        <el-table-column align="center" label="工作要求" prop="jobRequirements" min-width="150">
        </el-table-column>

        <el-table-column align="center" label="是否回收附件" prop="isRecycle" width="120">
          <template slot-scope="scope">
            {{ getDictName('yesNoDict', scope.row.isRecycle) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="发布状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status!=null" :type="getPublishStatusType(scope.row.status)" size="mini">
              {{ scope.row.status == 0 ? '未发布' : '已发布' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.status != 0" 
              type="text" 
              size="mini" 
              @click="handleCancelPublish(scope.row.id)"
            >取消发布</el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="handleView(scope.row)">详情</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="publicpaginationview">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" small></el-pagination>
        </div>
    </div>

    <!-- 防汛文件弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="900px" @close="handleDialogClose">
      <el-form :model="formData" :rules="formRules" ref="addForm" label-width="150px" size="small" class="safe-form">
        <el-form-item label="来源单位：" prop="sourceUnit">
           <CompanySelect v-model="formData.sourceUnit" :disabled="false" />
        </el-form-item>
        
        <el-form-item label="接收单位：" prop="receivingUnit">
          <CompanySelect v-model="formData.receivingUnit" multiple :disabled="isReadonly" />
        </el-form-item>
        
        <el-form-item label="发布日期：" prop="releaseDate">
          <el-date-picker v-model="formData.releaseDate" :disabled="isReadonly" type="date" placeholder="年/月/日" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="发布主题：" prop="releaseTitle">
          <el-input v-model="formData.releaseTitle" :disabled="isReadonly" placeholder="请输入发布主题"></el-input>
        </el-form-item>

        <el-form-item label="工作要求：" prop="jobRequirements">
          <el-input 
            v-model="formData.jobRequirements" 
            :disabled="isReadonly" 
            type="textarea" 
            :rows="3"
            placeholder="请输入工作要求">
          </el-input>
        </el-form-item>

        <el-form-item label="是否回收附件：" prop="isRecycle">
          <el-select v-model="formData.isRecycle" :disabled="isReadonly" placeholder="请选择" style="width: 100%">
            <el-option 
              v-for="item in dictData.yesNoDict" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="兼容报送附件：" prop="isCompatibleAttachments">
          <el-select v-model="formData.isCompatibleAttachments" :disabled="isReadonly" placeholder="请选择" style="width: 100%">
            <el-option 
              v-for="item in dictData.yesNoDict" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发布状态：" prop="status">
          <el-select v-model="formData.status" :disabled="isReadonly" placeholder="请选择发布状态" style="width: 100%">
            <el-option label="未发布" :value="0"></el-option>
            <el-option label="已发布" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 附件管理区域 -->
      <div class="attachment-section">
        <h4 class="section-title">附件名称</h4>
        <el-button v-if="!isReadonly" type="primary" size="mini" @click="handleAddAttachment" style="margin-bottom: 10px;">新增附件</el-button>
        <el-table :data="formData.sonDTOS" border size="mini" style="margin-top: 10px;">
          <el-table-column align="center" label="附件名称" prop="name" min-width="200">
            <template slot-scope="scope">

              <DocumentUpload
                  v-model="scope.row.file"
                  :max-count="1"
                  :show-tips="false"
                  :disabled="isReadonly"
                  @change="handleAttachmentChange(scope.$index, $event)"
              />

            </template>
          </el-table-column>
          <el-table-column align="center" label="是否报送附件" prop="isCompatibleAttachments" width="120">
            <template slot-scope="scope">
              <el-select 
                v-if="!isReadonly" 
                v-model="scope.row.isCompatibleAttachments" 
                size="mini" 
                style="width: 80px;"
              >
                <el-option 
                  v-for="item in dictData.yesNoDict" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{ getDictName('yesNoDict', scope.row.isCompatibleAttachments) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80">
            <template slot-scope="scope">
              <el-button 
                v-if="!isReadonly" 
                type="text" 
                size="mini" 
                style="color: #f56c6c;" 
                @click="handleDeleteAttachment(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ isReadonly ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="!isReadonly" type="primary" @click="handleSubmit" :loading="submitLoading">保 存</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { getPreventionList, addPrevention, cancelPreventionRelease, deletePrevention, updatePrevention, getPreventionDetails } from '@/api/safe/fangjungongzuo/fangjunwendangfabu'
import { formatDate } from '@/utils/dateUtils'
import CompanySelect                                                                                                           from "@/components/commonSelect/companySelect.vue";
import {info}                                                                                                                  from "@/api";
import DocumentUpload                                                                                                          from "@/components/DocumentUpload.vue";

export default {
  name: 'FangjunWendangFabu',
  components: {DocumentUpload, CompanySelect},

  data() {
    return {
      // 字典数据
      dictData: {
        // 接收单位
        receivingUnitDict: [
          { id: '1', name: '各区房屋管理中心' },
          { id: '2', name: '各管理部门' },
          { id: '3', name: '各防汛责任单位' },
          { id: '4', name: '各街道办事处' }
        ],
        // 是否选项
        yesNoDict: [
          { id: '1', name: '是' },
          { id: '0', name: '否' }
        ]
      },
      user:null,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        sourceUnit: "",
        receivingUnit: "",
        releaseDate: "",
        releaseTitle: ""
      },
      total: 0,
      list: [],
      listLoading: false,
      dialogVisible: false,
      submitLoading: false,
      dialogTitle: "防汛文件新增",
      isReadonly: false,
      currentEditId: null,
      formData: {
        id: null,
        sourceUnit: "",
        receivingUnit: "",
        releaseDate: "",
        releaseTitle: "",
        jobRequirements: "",
        isRecycle: "",
        isCompatibleAttachments: "",
        status: 0, // 默认为未发布状态
        countAttachments: 0,
        sonDTOS: []
      },

      formRules: {
        sourceUnit: [
          { required: true, message: '请输入文件来源单位', trigger: 'blur' }
        ],
        receivingUnit: [
          { required: true, message: '请输入接收单位', trigger: 'blur' }
        ],
        releaseDate: [
          { required: true, message: '请选择发布时间', trigger: 'change' }
        ],
        releaseTitle: [
          { required: true, message: '请输入发布主题', trigger: 'blur' }
        ],
        jobRequirements: [
          { required: true, message: '请输入工作要求', trigger: 'blur' }
        ],
        isRecycle: [
          { required: true, message: '请选择是否回收附件', trigger: 'change' }
        ],
        isCompatibleAttachments: [
          { required: true, message: '请选择兼容报送附件', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择发布状态', trigger: 'change' }
        ]
      }
    };
  },

  computed: {
    // 根据发布状态返回标签类型
    getPublishStatusType() {
      return (status) => {
        switch (status) {
          case 0:
            return "warning"; // 未发布
          case 1:
            return "success"; // 已发布
          default:
            return "info";
        }
      };
    }
  },

  mounted() {
    this.getList();
    info().then(res => {
      this.user = res.data;
      console.log(this.user)
    })
  },

  methods: {
    // 通用字典名称查找方法
    getDictName(dictType, id) {
      const item = this.dictData[dictType].find(item => item.id === String(id));
      return item ? item.name : id;
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    // 获取列表数据
    getList() {
      this.listLoading = true;

      // 构建请求参数，过滤空值
      const params = {};
      Object.keys(this.listQuery).forEach(key => {
        if (this.listQuery[key] !== '') {
          params[key] = this.listQuery[key];
        }
      });

      // 调用防汛文件发布分页接口
      getPreventionList(params)
        .then(response => {
          this.listLoading = false;
          if (response.code == 200) {
            this.list = response.data.list || [];
            this.total = response.data.total || 0;
          } else {
            this.$message.error(response.message || '获取数据失败');
          }
        })
        .catch(error => {
        this.listLoading = false;
          console.error('获取防汛文件发布数据失败:', error);
          this.$message.error('获取数据失败，请检查网络连接');
        });
    },
    // 搜索
    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
      this.$message.success('查询完成');
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getList();
    },
    // 新建发布
    handleAddRecord() {
      this.dialogTitle = "防汛文件新增";
      this.isReadonly = false;
      this.currentEditId = null;
      this.dialogVisible = true;
      this.resetFormData();
      this.formData.sourceUnit = this.user.did?this.user.did+"":'';
    },
    // 弹窗关闭
    handleDialogClose() {
      this.resetFormData();
      this.$refs.addForm.resetFields();
    },
    // 重置表单数据
    resetFormData() {
      this.formData = {
        id: null,
        sourceUnit: "",
        receivingUnit: "",
        releaseDate: "",
        releaseTitle: "",
        jobRequirements: "",
        isRecycle: "",
        isCompatibleAttachments: "",
        status: 0, // 默认为未发布状态
        countAttachments: 0,
        sonDTOS: []
      };
    },

    // 表单提交
    handleSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.formData.sonDTOS.forEach(item=>{
            delete item.file
            delete item.status
          })
          const params = {
            preventionDocRelease: {...this.formData},
            attList: this.formData.sonDTOS
          }
          delete params.preventionDocRelease.sonDTOS


          // 根据是否有ID决定使用新增还是修改接口
          const apiCall = this.currentEditId ? updatePrevention(params) : addPrevention(params);
          apiCall
            .then(response => {
              this.submitLoading = false;
              if (response.code == 200) {
                this.dialogVisible = false;
                const action = this.currentEditId ? '修改' : '新建发布';
                this.$message.success(`${action}成功！`);
                this.getList(); // 刷新列表
              } else {
                this.$message.error(response.message || '操作失败');
              }
            })
            .catch(error => {
              this.submitLoading = false;
              console.error('保存防汛文件发布失败:', error);
              this.$message.error('操作失败，请检查网络连接');
            });
        } else {
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },
    // 查看详情
    handleView(row) {
      this.dialogTitle = "防汛文件详情";
      this.isReadonly = true;
      this.currentEditId = row.id;
      this.dialogVisible = true;

      // 调用详情接口获取完整数据
      this.getDetailData(row.id);
    },
    // 修改记录
    handleUpdate(row) {
      this.dialogTitle = "防汛文件修改";
      this.isReadonly = false;
      this.currentEditId = row.id;
      this.dialogVisible = true;

      // 调用详情接口获取完整数据
      this.getDetailData(row.id);
    },
    // 获取详情数据
    getDetailData(id) {
      getPreventionDetails(id)
        .then(response => {
          if (response.code == 200 && response.data) {
            this.formData = response.data.preventionDocRelease;
            this.formData.sonDTOS = response.data.attList;
      
            delete this.formData.createTime;
            // 转换数字类型为字符串类型以便下拉选择框正确显示
            if (this.formData.isRecycle !== undefined) {
              this.formData.isRecycle = this.formData.isRecycle.toString();
            }
            if (this.formData.isCompatibleAttachments !== undefined) {
              this.formData.isCompatibleAttachments = this.formData.isCompatibleAttachments.toString();
            }
            // 转换附件列表中的数字类型为字符串类型
            if (this.formData.sonDTOS && this.formData.sonDTOS.length > 0) {
              this.formData.sonDTOS.forEach(item => {
                if (item.isCompatibleAttachments !== undefined) {
                  item.isCompatibleAttachments = item.isCompatibleAttachments.toString();
                }
                item.file = [{
                  name: item.name,
                  url: item.url,
                  fileType: item.fileType,
                  size:item.filesize
                }]
              });
            }
          } else {
            this.$message.error(response.message || '获取详情失败');
          }
        })
        .catch(error => {
          console.error('获取防汛文件详情失败:', error);
          this.$message.error('获取详情失败，请检查网络连接');
        });
    },
    // 新增附件行
    handleAddAttachment() {
      this.formData.sonDTOS.push({
        name: "",
        url: "",
        fileType: "",
        file: [],
        isCompatibleAttachments: "1", // 使用字符串类型
        status: null
      });
    },
    
    // 处理附件变化
    handleAttachmentChange(index, fileList) {

      if (fileList && fileList.length > 0) {
        const file = fileList[0]; // 取第一个文件
        this.$set(this.formData.sonDTOS, index, {
          ...this.formData.sonDTOS[index],
          name: file.name,
          url: file.url,
          filesize: file.size,
          fileType: this.getFileExtension(file.name)
        });
      } else {
        // 文件被删除
        this.$set(this.formData.sonDTOS, index, {
          ...this.formData.sonDTOS[index],
          name: "",
          url: "",
          fileType: ""
        });
      }
    },



    // 获取文件扩展名
    getFileExtension(fileName) {
      return fileName.slice((fileName.lastIndexOf('.') - 1 >>> 0) + 2);
    },
    
    // 删除附件
    handleDeleteAttachment(index) {
      this.formData.sonDTOS.splice(index, 1);
      this.$message.success('附件删除成功');
    },
    
    // 格式化日期 - 使用工具类方法
    formatDate,


    // 取消发布
    handleCancelPublish(id) {
      this.$confirm('确认取消发布该文件？', '取消发布提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用取消发布接口
        cancelPreventionRelease(id)
          .then(response => {
            if (response.code == 200) {
        this.$message({
          type: 'success',
          message: '取消发布成功!'
              });
              this.getList(); // 刷新列表
            } else {
              this.$message.error(response.message || '取消发布失败');
            }
          })
          .catch(error => {
            console.error('取消发布失败:', error);
            this.$message.error('取消发布失败，请检查网络连接');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    // 删除记录
    handleDelete(id) {
      this.$confirm('此操作将删除该条内容，请确认是否继续操作？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        deletePrevention(id)
          .then(response => {
            if (response.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList(); // 刷新列表
            } else {
              this.$message.error(response.message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除防汛文件失败:', error);
            this.$message.error('删除失败，请检查网络连接');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
};
</script>

<style scoped>
/* 页面样式继承公共样式类 publicpageview, publicformview, publitableview */

/* 附件管理区域样式 */
.attachment-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.section-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 弹窗内表格样式 */
.attachment-section .el-table {
  background-color: #fff;
}

.attachment-section .el-table td {
  padding: 8px 0;
}

.attachment-section .el-table th {
  padding: 10px 0;
  background-color: #fafafa;
}
</style>